//
//  ViewController.m
//  xmpp即时通信
//
//  Created by student on 16/1/22.
//  Copyright © 2016年 123. All rights reserved.
//

#import "loginViewController.h"
#import "AppDelegate.h"
#import "WTabViewController.h"
@interface ViewController ()

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *rightConstraint;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UITextField *usernameTextField;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {
        self.leftConstraint.constant = 100;
        self.rightConstraint.constant = 100;
    }
    
    WUserMessage *user = [WUserMessage readUserMessage];
    
    if(user)
    {
        self.usernameTextField.text = user.name;
        self.passwordTextField.text = user.password;
    }
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
    [appDelegate sendUsername:^(NSString *user) {
        
        self.usernameTextField.text = user;
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)login:(UIButton *)sender
{
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.password = self.passwordTextField.text;
    appDelegate.name = self.usernameTextField.text;
    appDelegate.login = YES;
    __weak typeof(self) vc = self;
    [appDelegate connectToServer:^(BlockResultLoginType type) {
        if(type == BlockResultLoginFail)
        {
            NSLog(@"密码错误");
        }
        else if(type == BlockResultLoginSuccess)
        {
            [vc change];
        }
        else
        {
            NSLog(@"连接超时");
        }
    }];
}

- (void)change
{
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        
        WTabViewController *tab = [[WTabViewController alloc]init];
        [UIApplication sharedApplication].keyWindow.rootViewController = tab;
    }];
}

- (void)dealloc
{
    NSLog(@"%s",__FUNCTION__);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{

    [self.view endEditing:YES];
}

@end
